import { createOrder, getOrderList, getOrderDetail, cancelOrder, payOrder } from '@/api/order'

const state = {
  orderList: [],
  orderDetail: null,
  total: 0,
  loading: false
}

const mutations = {
  SET_ORDER_LIST: (state, { list, total }) => {
    state.orderList = list
    state.total = total
  },
  SET_ORDER_DETAIL: (state, detail) => {
    state.orderDetail = detail
  },
  SET_LOADING: (state, loading) => {
    state.loading = loading
  }
}

const actions = {
  // 创建订单
  createOrder({ commit }, orderData) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      createOrder(orderData)
        .then(response => {
          const { data } = response
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          commit('SET_LOADING', false)
        })
    })
  },

  // 获取订单列表
  getOrderList({ commit }, query) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      getOrderList(query)
        .then(response => {
          const { data } = response
          commit('SET_ORDER_LIST', {
            list: data.records || [],
            total: data.total || 0
          })
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          commit('SET_LOADING', false)
        })
    })
  },

  // 获取订单详情
  getOrderDetail({ commit }, id) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      getOrderDetail(id)
        .then(response => {
          const { data } = response
          commit('SET_ORDER_DETAIL', data)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          commit('SET_LOADING', false)
        })
    })
  },

  // 取消订单
  cancelOrder({ commit }, id) {
    return new Promise((resolve, reject) => {
      cancelOrder(id)
        .then(response => {
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 支付订单
  payOrder({ commit }, { id, paymentMethod }) {
    return new Promise((resolve, reject) => {
      payOrder(id, paymentMethod)
        .then(response => {
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 